<template>
  <div class="account">
    <h3 style="margin-top: 0;">主号信息</h3>

    <van-form @submit="submitMainAccountInfo">
      <van-cell-group inset>
        <van-field disabled v-model="mainAccount.expirationTime" name="expirationTime" placeholder="请输入到期时间"
          :rules="[{ required: true, message: '请输入到期时间' }]">
          <template #label>
            <van-icon name="clock-o" style="margin-right: 5px" />到期时间
          </template>
        </van-field>

        <van-field v-model="mainAccount.phoneNumber" name="phoneNumber"
          :rules="[{ required: true, message: '请输入手机号' }]">
          <template #label>
            <van-icon name="phone-o" style="margin-right: 5px" />手机号
          </template>
        </van-field>

        <van-field name="btn">
          <template #input>
            <van-button type="primary" size="large" block native-type="submit" class="submit-btn">
              获取接单TK
            </van-button>
          </template>
        </van-field>

        <van-field disabled v-model="mainAccount.token" name="token" label-align="top" placeholder="请先获取接单Token" style="
            margin: 10px auto; 
            width: 91%; 
            background-color: #FAFAFC; 
            border-radius: 5px;
          ">
          <template #input>
            <div style="
                width: 100%;
                height: 100px; 
                border: 1px solid #DFDFE5; 
                border-radius: 5px;
                overflow-y: auto;
                padding: 10px;
                white-space: pre-wrap;
                word-break: break-all;
                font-size: 12px;
                line-height: 1.5;
                color: #666;
                background-color: #f5f5f5;
              ">
              {{ mainAccount.token || '暂无Token' }}
            </div>
          </template>
        </van-field>
      </van-cell-group>
    </van-form>

    <h3>小号信息</h3>

    <van-cell-group inset>
      <van-field v-model="newAccountPhone" name="newAccountPhone" placeholder="输入小号手机号"
        :rules="[{ required: true, message: '请输入手机号' }]">
        <template #label>
          <van-icon name="phone-o" style="margin-right: 5px" />手机号
        </template>
      </van-field>

      <van-field name="btn">
        <template #input>
          <van-button type="success" size="large" block class="add-account-btn" @click="addAccount">
            <van-icon name="plus" style="margin-right: 5px" />
            添加小号
          </van-button>
        </template>
      </van-field>
    </van-cell-group>

    <div v-for="(account, index) in additionalAccounts" :key="index" class="additional-account">
      <van-cell-group inset>
        <van-field name="btn" class="account-title">
          <template #input>
            小号[{{ account.phone.slice(-4) }}]
          </template>
        </van-field>

        <van-field disabled v-model="account.token" name="token" label-align="top" placeholder="请先获取接单Token" style="
            margin: 10px auto; 
            width: 91%; 
            background-color: #FAFAFC; 
            border-radius: 5px;
          ">
          <template #input>
            <div style="
                height: 100px; 
                border: 1px solid #DFDFE5; 
                border-radius: 5px;
                overflow-y: auto;
                padding: 10px;
                white-space: pre-wrap;
                word-break: break-all;
                font-size: 12px;
                line-height: 1.5;
                color: #666;
                background-color: #f5f5f5;
              ">
              {{ account.token || '暂无Token' }}
            </div>
          </template>
        </van-field>

        <van-field name="btn">
          <template #input>
            <van-button type="primary" size="large" block class="submit-btn" @click="getToken(index)">
              更新
            </van-button>
            <div style="width: 10px;"></div>
            <van-button type="danger" size="large" block class="submit-btn" @click="removeAccount(index)">
              删除小号
            </van-button>
          </template>
        </van-field>
      </van-cell-group>
    </div>


  </div>
</template>

<script>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useStore } from 'vuex';
import { showNotify } from 'vant';
import { StorageUtil } from '@/utils/storage'
import { userApi, loginApi, subTokenApi } from '@/api'
import qs from 'qs'

export default {
  setup() {
    const store = useStore();
    const active = computed(() => store.state.active)

    watch(active, (newValue) => {
      if (newValue === '1') {
        getUserInfo()
      }
    })

    // 主账号状态
    const mainAccount = reactive({
      phoneNumber: '',
      expirationTime: '',
      token: ''
    });

    // 额外账号状态
    const additionalAccounts = ref([]);
    const newAccountPhone = ref('');

    // 验证手机号码
    const validatePhoneNumber = (phoneNumber) => {
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(phoneNumber);
    };

    // 提交主账号信息
    const submitMainAccountInfo = () => {
      // 验证主账号手机号码
      if (!validatePhoneNumber(mainAccount.phoneNumber)) {
        showNotify({ type: 'warning', message: '请输入正确的手机号' });
        return;
      }

      // 验证到期日期
      if (!mainAccount.expirationTime) {
        showNotify({ type: 'warning', message: '请输入到期时间' });
        return;
      }

      userApi.getUserToken(mainAccount.phoneNumber).then((retData) => {
        // 更新主账号tk
        mainAccount.token = retData
        saveConfig()
      }).catch(error => {
        showNotify({ type: 'danger', message: error });
        console.error('主账号获取tk错误:', error);
      })
    };

    // 保存配置
    const saveConfig = () => {
      // 获取卡密
      const cardKey = StorageUtil.getCardKey();

      loginApi.login(cardKey)
        .then(response => {
          // 使用解构赋值，确保不会意外覆盖其他属性
          response.phoneNumber = mainAccount.phoneNumber
          response.token = mainAccount.token
          // 调用API提交
          loginApi.updateUserConfig(response)
            .then(response => {
              // 保存主账号信息
              StorageUtil.setToken(mainAccount.token)
              StorageUtil.setUserInfo(response)
              showNotify({ type: 'success', message: '配置保存成功' });
            })
            .catch(error => {
              showNotify({ type: 'danger', message: error.message || '配置保存失败' });
            });
        })
        .catch(error => {
          console.error(error);
          showNotify({ type: 'danger', message: '获取加载失败！' });
        });
    };

    // 添加新账号
    const addAccount = () => {
      // 去除手机号码两端空格
      const trimmedPhone = newAccountPhone.value.trim();

      // 验证手机号码
      if (!trimmedPhone) {
        showNotify({ type: 'warning', message: '手机号不能为空' });
        return;
      }

      if (!validatePhoneNumber(trimmedPhone)) {
        showNotify({ type: 'warning', message: '请输入正确的手机号' });
        return;
      }

      // 检查账号数量限制
      if (additionalAccounts.value.length >= 5) {
        showNotify({ type: 'warning', message: '最多添加5个小号' });
        return;
      }

      // 手机号获取token
      userApi.getUserToken(trimmedPhone).then((retData) => {
        // 添加新账号 添加最前面
        additionalAccounts.value.unshift({
          phone: trimmedPhone,
          token: retData
        });

        // 获取卡密
        const cardKey = StorageUtil.getCardKey();

        // 准备保存的小号数据
        const subTokens = JSON.stringify(additionalAccounts.value);

        const param = qs.stringify({ cardKey, subTokens })

        // 调用保存小号接口
        subTokenApi.saveSubTokens(param)
          .then(() => {
            // 重置表单
            newAccountPhone.value = '';
            showNotify({ type: 'success', message: '小号添加成功' });
          })
          .catch(error => {
            // 如果保存失败，移除刚添加的账号
            additionalAccounts.value.shift();
            showNotify({ type: 'danger', message: '小号添加失败：' + error.message });
          });
      }).catch(error => {
        showNotify({ type: 'danger', message: error });
        console.error('主账号获取tk错误:', error);
      })
    };

    // 删除账号
    const removeAccount = (index) => {
      const removedAccount = additionalAccounts.value.splice(index, 1)[0];

      // 获取卡密
      const cardKey = StorageUtil.getCardKey();

      // 准备保存的小号数据
      const subTokens = JSON.stringify(additionalAccounts.value);

      const param = qs.stringify({ cardKey, subTokens })

      // 调用保存小号接口
      subTokenApi.saveSubTokens(param)
        .then(() => {
          showNotify({ type: 'success', message: '小号删除成功' });
        })
        .catch(error => {
          // 如果删除失败，恢复删除的账号
          additionalAccounts.value.splice(index, 0, removedAccount);
          showNotify({ type: 'danger', message: '小号删除失败：' + error.message });
        });
    };

    // 获取令牌
    const getToken = (index) => {
      try {
        // 获取当前小号的手机号
        const currentAccount = additionalAccounts.value[index];

        // 调用获取Token的API
        userApi.getUserToken(currentAccount.phone)
          .then((retData) => {
            // 更新当前小号的Token
            additionalAccounts.value[index].token = retData;

            // 获取卡密
            const cardKey = StorageUtil.getCardKey();

            // 准备保存的小号数据
            const subTokens = JSON.stringify(additionalAccounts.value);

            const param = qs.stringify({ cardKey, subTokens })

            // 调用保存小号接口
            subTokenApi.saveSubTokens(param)
              .then(() => {
                showNotify({
                  type: 'success',
                  message: `小号[${currentAccount.phone.slice(-4)}]Token更新成功`
                });
              })
              .catch(error => {
                showNotify({
                  type: 'danger',
                  message: `小号[${currentAccount.phone.slice(-4)}]Token保存失败：${error.message}`
                });
                console.error('小号Token保存失败:', error);
              });
          })
          .catch(error => {
            showNotify({
              type: 'danger',
              message: `小号[${currentAccount.phone.slice(-4)}]Token获取失败：${error}`
            });
            console.error('小号Token获取错误:', error);
          });
      } catch (error) {
        showNotify({ type: 'danger', message: '更新失败！' });
        console.error('更新失败！:', error);
      }
    };

    // 获取用户信息
    const getUserInfo = () => {
      // 在登录后处理日志轮询
      const cardKey = StorageUtil.getCardKey();
      loginApi.login(cardKey)
        .then(response => {
          mainAccount.phoneNumber = response.phoneNumber;
          mainAccount.expirationTime = response.expirationTime;
          mainAccount.token = response.token;
          additionalAccounts.value = JSON.parse(response.subTokens) || [];
        })
        .catch(error => {
          console.error('Login failed', error)
        })
    };
    getUserInfo()

    return {
      // 主账号信息
      mainAccount,
      // 额外账号列表
      additionalAccounts,
      // 新账号手机号
      newAccountPhone,
      // 提交主账号信息方法
      submitMainAccountInfo,
      // 添加账号方法
      addAccount,
      // 删除账号方法
      removeAccount,
      // 获取令牌方法
      getToken
    };
  }
}
</script>

<style lang="less" scoped>
.account {
  padding: 10px;
  background-color: #f5f5f5;

  .van-cell-group {
    position: relative;
    margin-bottom: 16px;
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  }

  .account-title {
    font-size: 18px;
    font-weight: 700;
    color: #323233;
    padding-bottom: 0;
  }

  /deep/.account-title.van-cell:after {
    border: none !important;
  }
}

.additional-account {
  margin-bottom: 16px;
}

.add-account-section {
  background-color: #E6EAFA;
  border-radius: 12px;
  padding: 15px;
  margin-top: 16px;

  .add-account-btn {
    background-color: #2051D8;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
